package com.ttbj.product.api.impl;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ttbj.constant.TXConstant;
import com.ttbj.constant.YingYan;
import com.ttbj.core.util.HttpClientUtilYH;
import com.ttbj.core.util.JsonTools;
import com.ttbj.location.service.LocationComponent;
import com.ttbj.product.api.LocationFacade;
import com.ttbj.product.bean.dto.CoordDto;
import com.ttbj.product.bean.dto.Distance;
import com.ttbj.product.bean.dto.EntitieDto;
import com.ttbj.product.bean.dto.PointDto;
import com.zywl.common.utils.DateUtils;
import cn.jiguang.common.utils.StringUtils;

@Service("locationFacade")
public class LocationFacadeImpl implements LocationFacade {
	public static final Logger logger = LoggerFactory.getLogger(LocationFacadeImpl.class);
	private static final Long SECOND = 1000L;

	@Autowired
	private LocationComponent locationComponent = null;

	@Override
	public String entityAdd(String name, String desc, String city, String district) throws IOException {
		/* 参数生成 */
		Map<String, String> map = locationComponent.genRequestMap();
		String entity = UUID.randomUUID().toString();
		if (!StringUtils.isEmpty(name)) {
			map.put("entity_desc", name);
		}
		map.put("entity_name", entity);
		/* 验证是否成功 */
		if (null != locationComponent.isSuccess(HttpClientUtilYH.doPost(YingYan.ENTITY_ADD_URL, map))) {
			return entity;
		}
		return null;
	}

	@Override
	public List<EntitieDto> aroundSearch(String lng, String lat) throws IOException {
		Map<String, String> map = locationComponent.getAroundSearchRequestMap(lng, lat); // 1.请求参数map
		List<EntitieDto> list = new ArrayList<EntitieDto>();
		JSONObject jo = locationComponent.isSuccess(HttpClientUtilYH.doGet(YingYan.ENTITY_AROUNDSEARCH_URL, map));// 2.调用鹰眼api获取到返回参数
		if (null != jo) {
			Integer total = (Integer) jo.get("total"); // 3.附近有无司机
			if (null != total && total.intValue() > 0) {
				list = JsonTools.GsonToList(jo.optString("entities"), EntitieDto.class);
			}
		}
		return list;
	}

	static String[] deleteFirst(String[] rudisArray) {
		String[] temp = new String[rudisArray.length - 1];
		System.arraycopy(rudisArray, 1, temp, 0, temp.length);
		return temp;
	}

	@Override
	public CoordDto getlatestpoint(String entity_name) throws Exception {
		Map<String, String> map = locationComponent.genRequestMap();
		map.put("entity_name", entity_name);
		map.put("coord_type_output", YingYan.COORD_TYPE_TX);
		JSONObject object = locationComponent.isSuccess(HttpClientUtilYH.doGet(YingYan.GET_LATEST_POINT_URL, map));
		System.out.println(object);
		if (null != object) {
			JSONObject jo = (JSONObject) object.get("latest_point");
			Double lng = (Double) jo.get("longitude");
			Double lat = (Double) jo.get("latitude");
			if (null != lng && null != lat) {
				return new CoordDto(String.valueOf(lng), String.valueOf(lat));
			}
		}
		return null;
	}

	@Override
	public List<PointDto> getTrack(String entity_name, String startDate) throws Exception {
		if (isLegalDate(startDate)) {
			return null;
		}
		Map<String, String> map = locationComponent.genRequestMap();
		map.put("entity_name", entity_name);
		map.put("coord_type_output", YingYan.COORD_TYPE_TX);
		map.put("start_time", String.valueOf(DateUtils.getDateStr2long(startDate) / SECOND));
		map.put("end_time", String.valueOf(System.currentTimeMillis() / SECOND));
		map.put("coord_type_output", YingYan.COORD_TYPE_TX);
		JSONObject object = locationComponent.isSuccess(HttpClientUtilYH.doGet(YingYan.GET_TRACK_URL, map));
		if (null != object) {
			PointDto start_point = JsonTools.GsonToBean(object.optString("start_point"), PointDto.class);
			PointDto end_point = JsonTools.GsonToBean(object.optString("end_point"), PointDto.class);
			List<PointDto> list = JsonTools.GsonToList(object.optString("points"), PointDto.class);
			if (null == list || list.isEmpty()) {
				list = new ArrayList<PointDto>();
			}
			if (null != start_point) {
				list.add(0, start_point);
			}
			if (null != end_point) {
				list.add(end_point);
			}
			return list;
		}
		return null;
	}

	@Override
	public Distance getDistance(CoordDto from, CoordDto to) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("from", Obj2Str(from));
		map.put("to", Obj2Str(to));
		map.put("key", TXConstant.Key);
		map.put("policy", "PICKUP,NAV_POINT_FIRST");
		JSONObject jo = locationComponent.isSuccess(HttpClientUtilYH.doGet(TXConstant.DISTANCE_URL, map));
		if (null == jo) {
			return null;
		}
		JSONObject result = jo.getJSONObject("result");
		if (null == result) {
			return null;
		}

		System.out.println("optString--" + result);
		List<Distance> list = JsonTools.GsonToList(result.optString("elements"), Distance.class);
		if (null == list || list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	public String Obj2Str(CoordDto dto) {
		return new StringBuffer(dto.getLat()).append(",").append(dto.getLng()).toString();
	}

	/**
	 * 验证参数是否是日期
	 * 
	 * @param time
	 *            格式：yyyy-MM-dd HH:mm:ss
	 * @throws ParseException
	 */
	private boolean isLegalDate(String time) throws ParseException {
		int legalLen = 10;
		if ((StringUtils.isEmpty(time)) || (time.length() != legalLen)) {
			return false;
		}
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = formatter.parse(time);
		return time.equals(formatter.format(date));
	}

	@Override
	public List<Map<String, List<PointDto>>> allTrack(List<String> entitys, String startDate) throws Exception {
		List<Map<String, List<PointDto>>> list = new ArrayList<Map<String, List<PointDto>>>();
		Map<String, List<PointDto>> map = new HashMap<String, List<PointDto>>();
		entitys.stream().forEach(entity -> transTrack(list, map, entity, startDate));
		return list;
	}
	
	

	private List<Map<String, List<PointDto>>> transTrack(List<Map<String, List<PointDto>>> list, Map<String, List<PointDto>> map, String entity, String startDate) {
		try {
			map.put(entity, getTrack(entity, startDate));
			list.add(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
